package tp1.presentacion.controlador;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tp1.presentacion.modelo.Provincia;
import tp1.presentacion.modelo.ProvinciaLogic;

/**
 * Servlet implementation class ProvinciaController
 */
public class ProvinciaController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProvinciaController() {
        super();
        // TODO Auto-generated constructor stub
        ;
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getPathInfo();
		if(url.equals("/listar")) {
			this.listarProvincias(request, response);
		} else if(url.equals("/nuevo")) {
			response.sendRedirect("nuevaProv.jsp");
		} else if(url.equals("/registrar")) {
			this.registrarProvincia(request, response);
		}
	}
	
	private void registrarProvincia(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProvinciaLogic pLog = new ProvinciaLogic();
		String nomProv = request.getParameter("nomProv");
		Provincia provincia = new Provincia();
		provincia.setCodigo(0);
		provincia.setNombre(nomProv);
		pLog.agregar(provincia);
		response.sendRedirect("index.jsp");
	}
	private void listarProvincias(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProvinciaLogic pLog = new ProvinciaLogic();
		ArrayList<Provincia> provs = pLog.getTodos();
		request.setAttribute("provs", provs);
		RequestDispatcher rdis = request.getRequestDispatcher("/listProv.jsp");
		rdis.forward(request, response);		
	}
}